<template>
    <div id="msg">
        <div class="title">
            <span>试卷列表</span>
            <span>/ {{formData.examName}}</span>
        </div>
        <div class="wrapper">
            <ul class="top">
                <li class="example">{{formData.examName}}</li>

                <li class="right">
                    <div>
                        <span class="count">总分</span>
                        <span class="score">{{formData.grade}}</span>
                    </div>
                </li>
            </ul>
            <ul class="bottom">
                <li>考试截止时间：{{ formData.endTime }}</li>
                <li class="btn">{{ formData.examName }}</li>
                <li class="right"><el-button style="font-size: 22px;"
                    @click="toAnswer(formData.examId)">{{ $store.state.isPractice == true ? ' 开始练习' : ' 开始考试' }}</el-button></li>
            </ul>
        </div>
        <div class="content">
            <el-collapse>
                <el-collapse-item class="header" name="0">
                    <template slot="title">
                        <div class="title">
                            <span>{{formData.examName}}</span><i class="header-icon el-icon-a-041"></i>
                            <span class="time">{{formData.grade}}分/{{formData.examDuration}}分钟</span>
                            <el-button type="primary" size="small">试题</el-button>
                        </div>
                    </template>
                    <el-collapse class="inner">
                      <el-collapse-item>
                        <template slot="title">
                          <div class="title">单选题(共{{formData.type[0]}}题 共计{{formData.score[0]}}分)</div>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item>
                        <template slot="title">
                          <div class="title">多选题(共{{formData.type[1]}}题 共计{{formData.score[1]}}分)</div>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item>
                        <template slot="title">
                          <div class="title">判断题(共{{formData.type[2]}}题 共计{{formData.score[2]}}分)</div>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item>
                        <template slot="title">
                          <div class="title">填空题(共{{formData.type[3]}}题 共计{{formData.score[3]}}分)</div>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item>
                        <template slot="title">
                          <div class="title">主观题(共{{formData.type[4]}}题 共计{{formData.score[4]}}分)</div>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item>
                        <template slot="title">
                          <div class="title">其他类型(共{{formData.type[5]}}题 共计{{formData.score[5]}}分)</div>
                        </template>
                      </el-collapse-item>
                    </el-collapse>
                </el-collapse-item>
            </el-collapse>
        </div>
    </div>
</template>


<script>
import { insert, update, getExamDate,getList } from '@/api/Questions/index';
import { get } from '@/api/Exam/index';
import { update as updateExamStuent} from '@/api/ExamStudent/index';
import { Message } from 'element-ui';
export default {
  data() {
    return {
      formData: {
        id: null, // 用于区分添加和修改
        grade: null,
        type: [0,0,0,0,0,0],//所有题目类型
        score:[0,0,0,0,0,0],//所有题型对应的分数
        examId: null,
        examName: '' // 新增字段用于存储考试名称
      },
      rules: {
        questionName: [
          { required: true, message: '请输入题目名称', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' },
          { validator: this.validateAnswer, trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请输入分数', trigger: 'blur' }
        ],
        types: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        examId: [
          { required: true, message: '请选择所属考试', trigger: 'change' }
        ]
      },
      examIdOptions: [] // 考试选项
    };
  },
  methods: {

    getTableDataList() {
        console.log("question查找:",this.formData);
      getList(this.formData).then((res) => {
        console.log("打印题目返回集:",res.data.records);
                // 遍历返回的题目数据
        res.data.records.forEach(record => {
            const typeIndex = record.types; // 获取题目类型对应的下标
            const grade = record.grade; // 获取题目的分数

            // 如果 typeIndex 有效（非空且为数字），更新 formData.type 和 formData.score
            if (typeIndex !== null && !isNaN(typeIndex)) {
                // 更新 formData.type 的对应下标值
                if (this.formData.type[typeIndex] === undefined) {
                    this.formData.type[typeIndex] = 0; // 如果未定义，初始化为 0
                }
                this.formData.type[typeIndex] += 1; // 题目数量加 1

                // 更新 formData.score 的对应下标值
                if (this.formData.score[typeIndex] === undefined) {
                    this.formData.score[typeIndex] = 0; // 如果未定义，初始化为 0
                }
                this.formData.score[typeIndex] += grade; // 累加分数
            }
        });

        // 将 formData.score 中的所有值累加到 formData.grade
        this.formData.score.forEach(score => {
            if (score !== undefined) {
                this.formData.grade += score; // 累加总分
            }
        });


        console.log("更新后的 formData.type:", this.formData.type);
        console.log("更新后的 formData.score:", this.formData.score);
        console.log("更新后的总分：",this.formData.grade);
        }).catch((error) => {
            console.error("获取题目数据失败:", error);
      })
    },

    // 更新多选题答案字符串
    updateAnswerString() {
     this.formData.answer = this.formData.answerArray.join('');
    }, 
    // 自定义答案验证
    validateAnswer(rule, value, callback) {
      if (this.formData.types === 1) {
        if (this.formData.answerArray.length === 0) {
          callback(new Error('请选择答案'));
        } else {
          callback();
        }
      } else {
        if (!value) {
          callback(new Error('请输入答案'));
        } else {
          callback();
        }
      }
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formData.types === 1) {
            // 多选题：将答案数组转换为字符串
            this.formData.answer = this.formData.answerArray.join('');
          }
          if (this.formData.id) {
            // 修改操作
            update(this.formData).then(() => {
              Message.success('修改成功');
              this.goBack();
            });
          } else {
            // 添加操作
            insert(this.formData).then(() => {
              Message.success('添加成功');
              this.goBack();
            });
          }
        }
      });
    },
    // 返回上一页
    goBack() {
      this.$router.back();
    },
    saveTakeTime() {
      this.formData.id=this.$route.query.Id;
      // 调用后端接口保存 formData
      console.log("要参加的考试为：",this.formData);
      return updateExamStuent(this.formData).then((res) => {
        Message.success('开始时间保存成功');
      }).catch((error) => {
        console.error('保存开始时间失败:', error);
        throw error; // 抛出错误，以便在调用处捕获
      });
    },
    toAnswer(examId){
      if(this.$route.query.takeTime == null)
      {
         // 获取当前时间
        const now = new Date();
        this.formData.takeTime = this.formatDate(now);

        // 调用后端接口保存数据
        this.saveTakeTime().then(() => {
          // 保存成功后跳转到答题页面
          this.$router.push({ path: "/TakeExam/answer", query: { examId: examId , takeTime:this.formData.takeTime} });
        }).catch((error) => {
          // 保存失败，提示用户
          Message.error('保存开始时间失败，请稍后重试');
          console.error('保存开始时间失败:', error);
        });
      }
      else{
        Message.success('已参考，返回中途答题界面');
        console.log("时间：",this.$route.query.takeTime)
        this.$router.push({path:"/TakeExam/answer",query:{examId:examId , takeTime:this.$route.query.takeTime}})
      }
      // this.$router.push({path:"/TakeExam/answer",query:{examId:examId}})
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
  },
  mounted() {
    // 获取路由参数中的 examId
    const examId = this.$route.query.examId;
    console.log("获取到的 examId:", examId); // 打印 examId
    if (examId) {
      // 调用 get 方法获取考试详情
      get(examId).then((res) => {
        const examData = res.data; // 假设返回的数据中包含 examName
        console.log("res.date:",examData)
        this.formData.endTime=examData.endTime;
        this.formData.examDuration=examData.examDuration;
        this.formData.examName = examData.examName; // 绑定考试名称
        this.formData.examId = examId; // 保留 examId
        console.log("获取到的 formdata.examId:", this.formData.examId); // 打印 examId
        this.getTableDataList();
        // this.getTableDataList();
      }).catch((error) => {
        console.error("获取考试信息失败:", error);
        this.$message.error("获取考试信息失败，请稍后重试");
      });
    }
    // 获取考试选项
    getExamDate().then((res) => {
      this.examIdOptions = res.data;
    });
    // 如果有 id 参数，加载试题数据
    const id = this.$route.query.id;
    if (id) {
      get(id).then((res) => {
        const data = res.data;
        if (data.types === 1) {
          // 多选题：将字符串转换为数组
          data.answerArray = data.answer.split('');
        } else {
          data.answerArray = [];
        }
        this.formData = { ...data };
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.bottom {
  .right {
    .el-button {
      color: #409EFF;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
    }
  }
}

.right {
  margin-left: auto;
}

.inner .contenti .question {
  margin-left: 40px;
  color: #9a9a9a;
  font-size: 14px;
}

.content .inner .titlei {
  margin-left: 20px;
  font-size: 16px;
  color: #88949b;
  font-weight: bold;
}

.content .title .time {
  font-size: 16px;
  margin-left: 420px;
  color: #999;
}

.content .stitle {
  background-color: #0195ff;
}

.content .title span {
  margin-right: 10px;
}

#msg .content .title {
  font-size: 20px;
  margin: 0px;
  display: flex;
  align-items: center;
}

.content {
  margin-top: 20px;
  background-color: #fff;
}

.content .header {
  padding: 10px 30px;
}

.wrapper .info {
  margin: 20px 0px 0px 20px;
  border-top: 1px solid #eee;
  padding: 20px 0px 10px 0px;
}

.wrapper .info a {
  color: #88949b;
  font-size: 14px;
}

.wrapper .info a:hover {
  color: #0195ff;
}

.wrapper .bottom .btn {
  cursor: pointer;
  padding: 5px 10px;
  border: 1px solid #88949b;
  border-radius: 4px;
}

.wrapper .bottom {
  display: flex;
  margin-left: 20px;
  color: #999;
  font-size: 14px;
  align-items: center;
}

.wrapper .bottom li {
  margin-right: 14px;
}

#msg {
  background-color: #eee;
  width: 980px;
  margin: 0 auto;
}

#msg .title {
  margin: 20px;
}

#msg .wrapper {
  background-color: #fff;
  padding: 10px;
}

#msg ul {
  list-style-type: none; /* 移除项目符号 */
}

#msg li {
  list-style-type: none; /* 确保每个 li 也没有项目符号 */
}

.wrapper .top {
  display: flex;
  margin: 20px;
  align-items: center;
}

.wrapper .top .right {
  margin-left: auto;
}

.wrapper .top .example {
  color: #333;
  font-size: 22px;
  font-weight: 700;
}

.wrapper .top li i {
  margin-left: 20px;
  color: #88949b;
}

.wrapper .right .count {
  margin-right: 60px;
  color: #fff;
  padding: 4px 10px;
  background-color: #88949b;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  border: 1px solid #88949b;
}

.wrapper .right .score {
  position: absolute;
  left: 53px;
  top: -5px;
  padding: 1px 12px;
  font-size: 20px;
  color: #88949b;
  border: 1px dashed #88949b;
  border-left: none;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  font-weight: bold;
}

.wrapper .right div {
  position: relative;
}
</style>